package com.yinhai.message.implement.dwr.adapter;

import javax.annotation.Resource;

import com.yinhai.core.common.api.config.impl.SysConfig;
import com.yinhai.message.implement.dwr.sender.CacheMessageSender;
import com.yinhai.message.implement.dwr.sender.WebSocketMessageSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.yinhai.message.api.util.MessageType;
import com.yinhai.message.api.vo.TMMessageVo;
import com.yinhai.message.core.adapterManager.IAdapter;
import com.yinhai.message.core.event.IMessageEvent;
import com.yinhai.message.core.exception.ResultsHandle;
import com.yinhai.message.implement.dwr.event.DwrMessageEvent;
import com.yinhai.message.implement.dwr.sender.DwrMessageSender;
import com.yinhai.message.implement.dwr.sender.SendMessageCluster;

@Component("dwrAdapter")
public class DwrAdapter implements IAdapter, ApplicationListener<DwrMessageEvent>{

	private static final Logger LOGGER = LoggerFactory.getLogger(DwrAdapter.class);

	@Resource(name = "resultsHandle")
	private ResultsHandle resultsHandle;

	@Resource(name = "webSocketMessageSender")
	private WebSocketMessageSender webSocketMessageSender;
	@Resource(name = "cacheMessageSender")
	private CacheMessageSender cacheMessageSender;
	@Resource(name = "dwrMessageSender")
	private DwrMessageSender dwrMessageSender;
	
	@Resource(name = "sendMessageCluster")
	private SendMessageCluster sendMessageCluster;

	@Override
	public String getSenderType() {
		return MessageType.DWR;
	}
	
	@Override
	public IMessageEvent getEven(TMMessageVo vo) {
		return new DwrMessageEvent(vo);
	}
	
	@Async
	@Override
	public void onApplicationEvent(DwrMessageEvent event) {
		LOGGER.debug("dwr处理事件===============================================");
		TMMessageVo messageSendVO = event.getMessageVo();
		String mgid = messageSendVO.getMessage().getMgid();
		String tt = SysConfig.getSysConfig("msgSendType");
		if("dwr".equals(tt)){
			dwrMessageSender.sendMessage(messageSendVO);
			sendMessageCluster.send(messageSendVO);
		}else if("redis".equals(tt)){
			cacheMessageSender.sendMessage(messageSendVO);
		}else if("webSocket".equals(tt)){
			webSocketMessageSender.sendMessage(messageSendVO);
		}//轮询
		else if("poll".equals(tt)){
			System.out.println("轮询");
		}
		resultsHandle.handleResults(messageSendVO.getUserlist(), mgid, getSenderType());
	}

}
